// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import { Form, Radio, Table, Button, Popconfirm, Modal, Row, Col, Input, Select, Cascader, Icon, Checkbox, Tabs, DatePicker, message } from 'antd'
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'
// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
// 当前组件样式
import styles from './groupWeekReportDetailStyle.less'
import { CollapsiblePanels } from 'widget/CollapsiblePanels/index'
import { Grid } from 'widget/Grid/index'
import moment from 'moment';

const FormItem = Form.Item
const { RangePicker } = DatePicker
const { Option } = Select;
const { TextArea } = Input;
/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */
const groupWeekReportDetailView = function ({ dispatch, model, form }) {
  // 表单的子函数
  const { resetFields, getFieldDecorator, validateFields, setFieldsValue, validateFieldsAndScroll } = form
  // 取出model对象，命名空间
  const { modelObj, namespace } = model
  let { weekInitType, query, actionType, btnLoading, loading, isShow, competitorOpeningQuotationList, competitorOpeningCount } = modelObj

  const formItemLayoutPro = {
    labelCol: { span: 6 },
    wrapperCol: { span: 14 },
  };

  const columns1 = [
    {
      title: '序号', dataIndex: 'ruleNo', key: 'ruleNo', width: 120,
      render: (a, item, index, d, e, f) => {
        return index + 1
      },
    },
    {
      title: '区域', dataIndex: 'area', key: 'area',
      render: function (value, item, index) {
        return item.area
      }
    },
    {
      title: '城市数量', dataIndex: 'citycount', key: 'citycount',
      render: function (value, item, index) {
        return item.citycount
      }
    },
    {
      title: '我司操盘', dataIndex: 'procount', key: 'procount',
      render: function (value, item, index) {
        return item.procount
      }
    },
    {
      title: '监控竞品', dataIndex: 'competcount', key: 'competcount',
      render: function (value, item, index) {
        return item.competcount
      }
    },
  ]
  const columns2 = [
    {
      title: '区域', dataIndex: 'areaName', key: 'areaName', width: 200,
      render: function (value, item, index) {
        return item.areaName
      }
    },
    {
      title: '城市', dataIndex: 'cityName', key: 'cityName', width: 200,
      render: function (value, item, index) {
        if (item.cityName) {
          return <a style={{ color: '#0877fd' }} onClick={() => goPolicyEdit(item.id)}>{item.cityName}</a>
        } else {
          return ''
        }
      }
    },
    {
      title: '市场信号', dataIndex: 'marketSignal', key: 'marketSignal', width: 200,
      render: function (value, item, index) {
        return item.marketSignal
      }
    },
    {
      title: '政策异动内容', dataIndex: 'abnormalPolicy', key: 'abnormalPolicy', width: 600,
      render: (text, item, index) => {
        return (<div style={{ maxHeight: '60px', overflowY: 'auto', whiteSpace: 'normal' }} dangerouslySetInnerHTML={{ __html: text }}>
        </div>)
      }
    },
  ]
  const columns3 = [
    {
      title: '竞得单位', dataIndex: 'brand', key: 'brand',
      render: function (value, item, index) {
        return item.brand
      }
    },
    {
      title: '成交楼面价(元/m²)', dataIndex: 'realHousePrice', key: 'realHousePrice',
      render: function (value, item, index) {
        return item.realHousePrice
      }
    },
    {
      title: '周边项目售价区间(元/m²)', dataIndex: 'averagePrice', key: 'averagePrice',
      render: function (value, item, index) {
        return item.averagePrice
      }
    },
    {
      title: '城市', dataIndex: 'areaName', key: 'areaName', width: 200,
      render: (a, item, index, d, e, f) => {
        return item.areaName
      },
    },
    {
      title: '所在位置', dataIndex: 'address', key: 'address',
      render: function (value, item, index) {
        return item.address
      }
    },
    {
      title: '土地用途', dataIndex: 'landUse', key: 'landUse',
      render: function (value, item, index) {
        return item.landUse
      }
    },
    {
      title: '土地面积(m²)', dataIndex: 'landArea', key: 'landArea',
      render: function (value, item, index) {
        return item.landArea
      }
    },
    {
      title: '土地面积(亩)', dataIndex: 'landArea1', key: 'landArea1',
      render: function (value, item, index) {
        return Math.round(parseFloat(item.landArea / 666.66) * 100) / 100
      }
    },
    {
      title: '容积率', dataIndex: 'plotRatio', key: 'plotRatio',
      render: function (value, item, index) {
        return item.plotRatio
      }
    },
    {
      title: '溢价率(%)', dataIndex: 'premiumRates', key: 'premiumRates',
      render: function (value, item, index) {
        return item.premiumRates + '%'
      }
    }
  ]
  const columns4 = [
    {
      title: '区域', dataIndex: 'areaName', key: 'areaName', width: 120,
      render: function (value, item, index) {
        return item.areaName
      }
    },
    {
      title: '城市片区', dataIndex: 'address', key: 'address', width: 120,
      render: function (value, item, index) {
        return item.address
      }
    },
    {
      title: '竞品', dataIndex: 'competingGoodsName', key: 'competingGoodsName', width: 140,
      render: function (value, item, index) {
        if (item.competingGoodsName) {
          return <a style={{ color: '#0877fd' }} onClick={() => goWeekReportDetail(item)}>{item.competingGoodsName}</a>
        } else {
          return ""
        }
      }
    },
    {
      title: '业态', dataIndex: 'productType', key: 'productType', width: 120,
      render: function (value, item, index) {
        return item.productType
      }
    },
    {
      title: '本周均价', dataIndex: 'averagePrice', key: 'averagePrice', width: 160,
      render: function (value, item, index) {
        return item.averagePrice
      }
    },
    {
      title: '环比(±%)', dataIndex: 'priceRatio', key: 'priceRatio', width: 120,
      sorter: (a, b) => a.priceRatio - b.priceRatio,
      render: function (value, item, index) {
        return item.priceRatio + "%"
      }
    },
    {
      title: '均价环比浮动原因', dataIndex: 'reason', key: 'reason', width: 400,
      render: function (value, item, index) {
        if (isShow) {
          return (<div>
            <TextArea value={item.reason} style={{ width: '76%', marginRight: '12px' }} disabled={true} onChange={(e) => { tableChange(e.target.value, 'reason', item) }} />
            <Button onClick={e => tabShowFun()} disabled={actionType == 'check'} type='primary'>{'修改'}</Button>
          </div>)
        } else {
          return (<div>
            <TextArea value={item.reason} style={{ width: '76%', marginRight: '12px' }} disabled={false} onChange={(e) => { tableChange(e.target.value, 'reason', item) }} />
            <Button type='primary' onClick={e => editFun(item.weeklyInformationId, item.reason)}>{'保存'}</Button>
          </div>)
        }
      }
    },
  ]
  const columns5 = [
    {
      title: '区域', dataIndex: 'areaName', key: 'areaName', width: 260,
      render: function (value, item, index) {
        const obj = {
          children: value,
          props: {},
        };
        const arrResult = mergeCells(competitorOpeningQuotationList);
        for (let i = 0; i < arrResult[0].length; i++) {
          if (index === arrResult[1][i]) {
            obj.props.rowSpan = arrResult[0][i];
            obj.children = item.areaName
          }
          if (index > arrResult[1][i] && index < arrResult[1][i + 1]) {
            obj.props.rowSpan = 0;
          }
        }
        return obj;
      }
    },
    {
      title: '开盘时间', dataIndex: 'openingTime', key: 'openingTime', width: 160,
      render: function (value, item, index) {
        const obj = {
          children: value,
          props: {},
        };
        const arrResult = mergeCells(competitorOpeningQuotationList);
        for (let i = 0; i < arrResult[0].length; i++) {
          if (index === arrResult[1][i]) {
            obj.props.rowSpan = arrResult[0][i];
            obj.children = item.openingTime
          }
          if (index > arrResult[1][i] && index < arrResult[1][i + 1]) {
            obj.props.rowSpan = 0;
          }
        }
        return obj;
      }
    },
    {
      title: '我司项目', dataIndex: 'ourProjects', key: 'ourProjects', width: 180,
      render: function (value, item, index) {
        const obj = {
          children: value,
          props: {},
        };
        const arrResult = mergeCells(competitorOpeningQuotationList);
        for (let i = 0; i < arrResult[0].length; i++) {
          if (index === arrResult[1][i]) {
            obj.props.rowSpan = arrResult[0][i];
            obj.children = item.ourProjects;
          }
          if (index > arrResult[1][i] && index < arrResult[1][i + 1]) {
            obj.props.rowSpan = 0;
          }
        }
        return obj;
      }
    },
    {
      title: '开盘竞品', dataIndex: 'competingGoodsName', key: 'competingGoodsName', width: 180,
      render: function (value, item, index) {
        const obj = {
          children: value,
          props: {},
        };
        const arrResult = mergeCells(competitorOpeningQuotationList);
        for (let i = 0; i < arrResult[0].length; i++) {
          if (index === arrResult[1][i]) {
            obj.props.rowSpan = arrResult[0][i];
            obj.children = item.competingGoodsName;
          }
          if (index > arrResult[1][i] && index < arrResult[1][i + 1]) {
            obj.props.rowSpan = 0;
          }
        }
        return obj;
      }
    },
    {
      title: '开盘批次', dataIndex: 'openingPi', key: 'openingPi', width: 180,
      render: function (value, item, index) {
        const obj = {
          children: value,
          props: {},
        };
        const arrResult = mergeCells(competitorOpeningQuotationList);
        for (let i = 0; i < arrResult[0].length; i++) {
          if (index === arrResult[1][i]) {
            obj.props.rowSpan = arrResult[0][i];
            obj.children = item.openingPi;
          }
          if (index > arrResult[1][i] && index < arrResult[1][i + 1]) {
            obj.props.rowSpan = 0;
          }
        }
        return obj;
      }
    },
    {
      title: '开盘方式', dataIndex: 'openingMethod', key: 'openingMethod', width: 180,
      render: function (value, item, index) {
        const obj = {
          children: value,
          props: {},
        };
        const arrResult = mergeCells(competitorOpeningQuotationList);
        for (let i = 0; i < arrResult[0].length; i++) {
          if (index === arrResult[1][i]) {
            obj.props.rowSpan = arrResult[0][i];
            obj.children = item.openingMethod
          }
          if (index > arrResult[1][i] && index < arrResult[1][i + 1]) {
            obj.props.rowSpan = 0;
          }
        }
        return obj;
      }
    },
    {
      title: '产品类型', dataIndex: 'productType', key: 'productType', width: 180,
    },
    {
      title: '产品户型', dataIndex: 'productHouseType', key: 'productHouseType', width: 180,
    },
    {
      title: '面积(m²)', dataIndex: 'area', key: 'area', width: 120,
    },
    {
      title: '开盘价格(元/m²)', dataIndex: 'openingPrice', key: 'openingPrice', width: 180,
    },
    {
      title: '开盘优惠', dataIndex: 'openingOffer', key: 'openingOffer', width: 200,
      render: function (value, item, index) {
        const obj = {
          children: value,
          props: {},
        };
        const arrResult = mergeCells(competitorOpeningQuotationList);
        for (let i = 0; i < arrResult[0].length; i++) {
          if (index === arrResult[1][i]) {
            obj.props.rowSpan = arrResult[0][i];
            obj.children = item.openingOffer;
          }
          if (index > arrResult[1][i] && index < arrResult[1][i + 1]) {
            obj.props.rowSpan = 0;
          }
        }
        return obj;
      }
    },
    {
      title: '总认筹数（套）', dataIndex: 'totalSubscription', key: 'totalSubscription', width: 120,
      render: function (value, item, index) {
        const obj = {
          children: value,
          props: {},
        };
        const arrResult = mergeCells(competitorOpeningQuotationList);
        for (let i = 0; i < arrResult[0].length; i++) {
          if (index === arrResult[1][i]) {
            obj.props.rowSpan = arrResult[0][i];
            obj.children = item.totalSubscription
          }
          if (index > arrResult[1][i] && index < arrResult[1][i + 1]) {
            obj.props.rowSpan = 0;
          }
        }
        return obj;
      }
    },
    {
      title: '总货量（套）', dataIndex: 'totalVolume', key: 'totalVolume', width: 120,
      render: function (value, item, index) {
        const obj = {
          children: value,
          props: {},
        };
        const arrResult = mergeCells(competitorOpeningQuotationList);
        for (let i = 0; i < arrResult[0].length; i++) {
          if (index === arrResult[1][i]) {
            obj.props.rowSpan = arrResult[0][i];
            obj.children = item.totalVolume;
          }
          if (index > arrResult[1][i] && index < arrResult[1][i + 1]) {
            obj.props.rowSpan = 0;
          }
        }
        return obj;
      }
    },
    {
      title: '总货值（万元）', dataIndex: 'totalValue', key: 'totalValue', width: 140,
      render: function (value, item, index) {
        const obj = {
          children: value,
          props: {},
        };
        const arrResult = mergeCells(competitorOpeningQuotationList);
        for (let i = 0; i < arrResult[0].length; i++) {
          if (index === arrResult[1][i]) {
            obj.props.rowSpan = arrResult[0][i];
            obj.children = item.totalValue
          }
          if (index > arrResult[1][i] && index < arrResult[1][i + 1]) {
            obj.props.rowSpan = 0;
          }
        }
        return obj;
      }
    },
    {
      title: '去化套数', dataIndex: 'removalSetNum', key: 'removalSetNum', width: 120,
      render: function (value, item, index) {
        const obj = {
          children: value,
          props: {},
        };
        const arrResult = mergeCells(competitorOpeningQuotationList);
        for (let i = 0; i < arrResult[0].length; i++) {
          if (index === arrResult[1][i]) {
            obj.props.rowSpan = arrResult[0][i];
            obj.children = item.removalSetNum;
          }
          if (index > arrResult[1][i] && index < arrResult[1][i + 1]) {
            obj.props.rowSpan = 0;
          }
        }
        return obj;
      }
    },
    {
      title: '去化率', dataIndex: 'removalRate', key: 'removalRate', width: 120,
      render: function (value, item, index) {
        const obj = {
          children: value,
          props: {},
        };
        const arrResult = mergeCells(competitorOpeningQuotationList);
        for (let i = 0; i < arrResult[0].length; i++) {
          if (index === arrResult[1][i]) {
            obj.props.rowSpan = arrResult[0][i];
            obj.children = item.removalRate;
          }
          if (index > arrResult[1][i] && index < arrResult[1][i + 1]) {
            obj.props.rowSpan = 0;
          }
        }
        return obj;
      }
    },
    {
      title: '开盘效果', dataIndex: 'openingEffect', key: 'openingEffect', width: 120,
      render: function (value, item, index) {
        const obj = {
          children: value,
          props: {},
        };
        const arrResult = mergeCells(competitorOpeningQuotationList);
        for (let i = 0; i < arrResult[0].length; i++) {
          if (index === arrResult[1][i]) {
            obj.props.rowSpan = arrResult[0][i];
            obj.children = item.openingEffect;
          }
          if (index > arrResult[1][i] && index < arrResult[1][i + 1]) {
            obj.props.rowSpan = 0;
          }
        }
        return obj;
      }
    },
    {
      title: '竞品开盘销情简析', dataIndex: 'competitorOpeningSalesAnalysis', key: 'competitorOpeningSalesAnalysis', width: 180,
      render: function (value, item, index) {
        const obj = {
          children: value,
          props: {},
        };
        const arrResult = mergeCells(competitorOpeningQuotationList);
        for (let i = 0; i < arrResult[0].length; i++) {
          if (index === arrResult[1][i]) {
            obj.props.rowSpan = arrResult[0][i];
            obj.children = item.competitorOpeningSalesAnalysis ? <TextArea rows={4} maxLength={300} key={index} value={item.competitorOpeningSalesAnalysis} readOnly /> : null
          }
          if (index > arrResult[1][i] && index < arrResult[1][i + 1]) {
            obj.props.rowSpan = 0;
          }
        }
        return obj;
      }
    },
    {
      title: '市场趋势判断', dataIndex: 'marketTrendJudgment', key: 'marketTrendJudgment', width: 180,
      render: function (value, item, index) {
        const obj = {
          children: value,
          props: {},
        };
        const arrResult = mergeCells(competitorOpeningQuotationList);
        for (let i = 0; i < arrResult[0].length; i++) {
          if (index === arrResult[1][i]) {
            obj.props.rowSpan = arrResult[0][i];
            obj.children = item.marketTrendJudgment ? <TextArea rows={4} maxLength={300} key={index} value={item.marketTrendJudgment} readOnly /> : null
          }
          if (index > arrResult[1][i] && index < arrResult[1][i + 1]) {
            obj.props.rowSpan = 0;
          }
        }
        return obj;
      }
    },
  ]
  // 合并单元格
  function mergeCells(dataSource) {
    let objResult = {};
    let arr = [];
    let arr1 = [];
    let arr2 = [0];
    let arrResult = [];
    let len = 0;
    let typeResult = null;
    dataSource.map((val) => {
      for (let i in val) {
        if (i === 'parentCode') {
          typeResult = val[i];
        }
      }
      let objArray = objResult[typeResult] || [];
      objArray.push(val);
      objResult[typeResult] = objArray;
    });
    for (let i in objResult) {
      arr.push(objResult[i]);
    }
    arr.map((val, key) => {
      arr1.push(val.length);
      len += val.length;
      arr2.push(len);
    });
    arrResult[0] = arr1;
    arrResult[1] = arr2;
    return arrResult;
  }
  //跳转客户列表
  function goWeekReportDetail(item) {
    let id = item && item.id ? item.id : ""
    let status = item && item.status ? item.status : ""
    hashHistory.push({
      pathname: '/home/predictManage/weekReportDetail',
      query: { actionType: status && status == '0' ? 'edit' : 'check', id: id }
    })
  }

  //跳转政策详情
  function goPolicyEdit(itemId) {
    hashHistory.push({
      pathname: '/home/predictManage/policyEdit',
      query: { actionType: 'edit', id: itemId }
    })
  }
  //日期改变时
  function dateChange(m, s) {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {
        query: {
          ...query,
          startTime: s[0],
          endTime: s[1],
        }
      }
    })
  }
  //输入框
  function inputChange(value, name) {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {
        query: {
          ...query,
          [name]: value,
        }
      }
    })
  }
  function txtAreaChange(value, name) {
    query.data.conclusion = value
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { query }
    })
  }


  //表格改变时
  function tableChange(value, name, data) {
    let obj = { [name]: value }
    for (var item of query.data.weeklyCompeting) {
      if (item.weeklyInformationId == data.weeklyInformationId) {
        item = Object.assign(item, obj)
      }
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { query }
    })
  }
  function tabShowFun() {
    isShow = false
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { isShow }
    })
  }
  function editFun(weeklyInformationId, reason) {
    dispatch({
      type: `${namespace}/updatepriceRatioReason`,
      payload: { id: weeklyInformationId, reason: reason }
    })
  }

  function submit(type) {
    validateFieldsAndScroll((err) => {
      if (err) {
        return false
      } else {
        dispatch({
          type: `${namespace}/submit`,
          payload: { type: type }
        })
      }
    })
  }
  return (
    <div className='public_listMain'>
      <div className={"functionButton"}>
        <Button disabled={actionType == 'check' || weekInitType == false} type='primary' onClick={e => submit('保存')} loading={btnLoading}>保存</Button>
        <Button disabled={actionType == 'check' || weekInitType == false} type='primary' onClick={e => submit('提交')} loading={loading}>发布</Button>
      </div>
      <div>
        <div style={{ textAlign: 'center', fontWeight: 600, fontSize: '18px', lineHeight: '46px' }}>美的置业集团周报摘要</div>
        <div>
          <div style={{ color: 'red', paddingLeft: '4%' }}>注：修改统计周期后，必须点击获取周报数据按钮生成新数据！</div>
          <Row>
            <Col span={8}>
              <FormItem
                {...formItemLayoutPro}
                label="统计周期"
              >
                {getFieldDecorator('effectiveTime', {
                  rules: [{ required: true, message: '请选择统计周期' },
                  ],
                  initialValue: query.startTime ? [moment(query.startTime, 'YYYY-MM-DD'), moment(query.endTime, 'YYYY-MM-DD')] : [],
                })(
                  <RangePicker disabled={actionType != 'add'} showTime={{
                    hideDisabledOptions: true,
                  }}
                    format="YYYY-MM-DD" onChange={(date, dateString) => { dateChange(date, dateString) }}
                    onOk={(date) => { }}
                  />
                )}
              </FormItem>
            </Col>
            <Col span={3}>
              <Button style={{ marginLeft: '50px', marginRight: '12px', marginTop: '4px' }} disabled={actionType == 'check'} type='primary' onClick={() => dispatch({ type: `${namespace}/getFirst` })}>获取周报数据</Button>
            </Col>
            <Col span={8}>
              <FormItem
                {...formItemLayoutPro}
                label="周报标题"
              >
                {getFieldDecorator('title', {
                  rules: [{ required: true, message: '请输入周报标题' },
                  ],
                  initialValue: query.title,
                })(
                  <Input disabled={actionType == 'check'} placeholder={'请输入周报标题'} onChange={(e) => { inputChange(e.target.value, 'title') }} />
                )}
              </FormItem>
            </Col>
          </Row>
        </div>
        <div>
          <div style={{ fontWeight: 600, fontSize: '15px', lineHeight: '46px' }}>我司本周业绩小结</div>
          <TextArea maxLength={400} disabled={actionType == 'check'} placeholder='请输入' rows={4} value={query.data.conclusion} onChange={(e) => { txtAreaChange(e.target.value, 'conclusion') }} />
        </div>
        <div>
          <div style={{ fontWeight: 600, fontSize: '15px', lineHeight: '46px' }}>进驻城市政策异动监测</div>
          <div style={{ marginBottom: '16px' }}>政策异动情况：</div>
          <Table columns={columns2} dataSource={query.data.weeklyPolicy} pagination={false} />
        </div>
        <div>
          <div style={{ fontWeight: 600, fontSize: '15px', lineHeight: '46px' }}>进驻城市土拍监测</div>
          <div style={{ marginBottom: '16px' }}>周报监测已进驻城市中，本周成交溢价率由高到低的地块如下：</div>
          <Table columns={columns3} dataSource={query.data.weeklyLand} pagination={false} />
        </div>
        <div>
          <div style={{ fontWeight: 600, fontSize: '15px', lineHeight: '46px' }}>我司项目对标竞品销售价格异动监测</div>
          <div style={{ marginBottom: '16px' }}>周报中统计的我司项目共{query.data.procount}个，监测竞品项目共{query.data.competcount}个，其中出现销售价格异动（竞品成交均价环比上周变动±5%以上）的竞品项目有{query.data.fivePointConut}个：</div>
          <Table columns={columns4} dataSource={query.data.weeklyCompeting} pagination={false} />
        </div>
        <div>
          <div style={{ fontWeight: 600, fontSize: '15px', lineHeight: '46px' }}>竞品开盘情况</div>
          <div style={{ marginBottom: '16px' }}>截止本周，监测竞品开盘项目共{competitorOpeningCount}个</div>
          <Table columns={columns5} scroll={{ x: '2800px' }} dataSource={competitorOpeningQuotationList} pagination={false} />
        </div>
        <div>
          <div style={{ margin: '16px 0' }}>截止本周，周报监测的已进驻城市（不含非操盘项目所在城市）供{query.data.citycount}个，我司操盘项目共{query.data.procount}个，共检测竞品项目共{query.data.competcount}个。</div>
          <Table columns={columns1} dataSource={query.data.weeklyInfo} pagination={false} />
        </div>
      </div>
    </div>
  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(groupWeekReportDetailView))